<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">编辑</el-button>
          <div v-else>
            <el-button type="success" @click="handleSave">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </div>
      </template>
      
      <el-form 
        :model="profileForm" 
        :rules="rules"
        ref="profileFormRef"
        label-width="100px"
        :disabled="!isEditing"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="profileForm.realName" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" />
        </el-form-item>
        <el-form-item v-show="false" label="部门" prop="department">
          <el-input v-model="profileForm.department" readonly />
        </el-form-item>
        <el-form-item v-show="false" label="职位" prop="position">
          <el-input v-model="profileForm.position" readonly />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <el-form 
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateProfile, updatePassword } from '@/api/user'

export default {
  name: 'Profile',
  setup() {
    const isEditing = ref(false)
    const profileFormRef = ref(null)
    const passwordFormRef = ref(null)

    // 个人信息表单数据
    const profileForm = reactive({
      username: '',
      realName: '',
      phone: '',
      email: '',
      department: '',
      position: ''
    })

    // 修改密码表单数据
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 个人信息验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      department: [],
      position: []
    }

    // 密码验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfo()
        if ((res.code === 200 || res.code === "200") && res.data) {
          // 适配新的API响应格式
          profileForm.username = res.data.username || '';
          profileForm.realName = res.data.realName || '';
          profileForm.phone = res.data.mobile || '';  // 使用mobile字段
          profileForm.email = res.data.email || '';
          profileForm.department = res.data.deptName || '';  // 使用deptName字段
          profileForm.position = res.data.roles && res.data.roles.length > 0 ? res.data.roles[0] : '';  // 使用角色作为职位
          
          // 可以在本地存储中更新用户信息
          localStorage.setItem('userInfo', JSON.stringify(res.data));
        } else {
          ElMessage.error(res.msg || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
      }
    }

    // 编辑个人信息
    const handleEdit = () => {
      isEditing.value = true
    }

    // 保存个人信息
    const handleSave = async () => {
      if (!profileFormRef.value) return
      
      // 确保部门有值，即使是隐藏字段
      if (!profileForm.department) {
        profileForm.department = '未分配部门'
      }
      
      try {
        await profileFormRef.value.validate()
        // 构建更新数据，适配新的API格式
        const updateData = {
          username: profileForm.username,
          realName: profileForm.realName,
          mobile: profileForm.phone,  // 使用mobile字段
          email: profileForm.email,
          deptName: profileForm.department // 部门字段已在上面设置了默认值
          // 由于职位是只读的，不需要更新这些字段
        }
        
        const res = await updateProfile(updateData)
        if (res.code === 200 || res.code === "200") {
          ElMessage.success(res.msg || '保存成功')
          isEditing.value = false
          // 重新获取用户信息
          await fetchUserInfo()
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 取消编辑
    const handleCancel = () => {
      isEditing.value = false
      profileFormRef.value?.resetFields()
      // 重新获取用户信息
      fetchUserInfo()
    }

    // 修改密码
    const handleChangePassword = async () => {
      if (!passwordFormRef.value) return

      try {
        await passwordFormRef.value.validate()
        const res = await updatePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          confirmPassword: passwordForm.confirmPassword
        })
        
        if (res.code === 200 || res.code === "200") {
          ElMessage.success(res.msg || '密码修改成功')
          passwordFormRef.value.resetFields()
        } else {
          ElMessage.error(res.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      }
    }

    // 组件挂载时获取用户信息
    onMounted(() => {
      fetchUserInfo()
    })

    return {
      isEditing,
      profileFormRef,
      passwordFormRef,
      profileForm,
      passwordForm,
      rules,
      passwordRules,
      handleEdit,
      handleSave,
      handleCancel,
      handleChangePassword
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  display: flex;
  gap: 20px;
}

.profile-card {
  flex: 2;
}

.password-card {
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 